<template>
  <div class="borrowing-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>借阅记录</span>
        </div>
      </template>
      
      <el-table :data="borrowRecords" style="width: 100%">
        <el-table-column prop="book.title" label="书名" />
        <el-table-column prop="borrowDate" label="借阅日期">
          <template #default="scope">
            {{ formatDate(scope.row.borrowDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="returnDate" label="应还日期">
          <template #default="scope">
            {{ formatDate(scope.row.returnDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="actualReturnDate" label="实际归还日期">
          <template #default="scope">
            {{ scope.row.actualReturnDate ? formatDate(scope.row.actualReturnDate) : '未归还' }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              v-if="!scope.row.actualReturnDate"
              type="primary"
              size="small"
              @click="returnBook(scope.row.id)"
            >
              归还
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { format } from 'date-fns'
import { ElMessage } from 'element-plus' 

export default {
  setup() {
    const borrowRecords = ref([])

    const loadBorrowRecords = async () => {
      try {
        const response = await axios.get('/api/borrow/my-records')
        borrowRecords.value = response.data
      } catch (error) {
        ElMessage.error('获取借阅记录失败')
      }
    }

    const returnBook = async (recordId) => {
      try {
        await axios.post(`/api/borrow/${recordId}/return`)
        ElMessage.success('归还成功')
        loadBorrowRecords()
      } catch (error) {
        ElMessage.error('归还失败')
      }
    }

    const formatDate = (date) => {
      return format(new Date(date), 'yyyy-MM-dd')
    }

    onMounted(() => {
      loadBorrowRecords()
    })

    return {
      borrowRecords,
      returnBook,
      formatDate
    }
  }
}
</script> 